package thread_synchronization;


import java.util.concurrent.*;


public class AccountWithoutSync {
    private static Account account = new Account();

    public static void main(String[] args) {
        ExecutorService executor = Executors.newCachedThreadPool();

        // 创建并发布100个线程
        for (int i = 0; i < 100; i++) {
            executor.execute(new AddAPennyTask());
        }
        executor.shutdown();

        // 等待所有任务完成
        while (!executor.isTerminated()) {

        }

        System.out.println("What is balance? " + account.getBalance());
    }

    // 给账户增加一分钱的线索
    private static class AddAPennyTask implements Runnable {
        public void run() {
            account.deposit(1);  //存款1元钱
        }
    }

    // An inner class for account
    private static class Account {
        private int balance = 0;

        public int getBalance() {
            return balance;
        }

        public synchronized void deposit(int amount) { // 隐性同步锁--同步关键字
            int newBalance = balance + amount;

            //故意添加的延迟会放大数据损坏问题，使其易于查看
            try {
                Thread.sleep(5);
            } catch (InterruptedException ex) {

            }

            balance = newBalance;
        }
    }

}
